import { defineStore } from "pinia";
import { store } from "@/store";
import { userType } from "./types";
import { routerArrays } from "@/layout/types";
import { router, resetRouter } from "@/router";
import { storageSession, storageLocal } from "@pureadmin/utils";
import { getLogin, refreshTokenApi, getLogout } from "@/api/user";
import { UserResult, RefreshTokenResult } from "@/api/user";
import { useMultiTagsStoreHook } from "@/store/modules/multiTags";
import { type DataInfo, setToken, removeToken, sessionKey } from "@/utils/auth";
import { ElMessage } from "element-plus";
import qs from "qs";
import { decrypt } from "@/utils/asc";
export const useUserStore = defineStore({
  id: "pure-user",
  state: (): userType => ({
    // 用户名
    username:
      storageLocal().getItem<DataInfo<number>>(sessionKey)?.username ?? "",
    // 页面级别权限
    roles: storageLocal().getItem<DataInfo<number>>(sessionKey)?.roles[0]
      ? [
          decrypt(
            storageLocal().getItem<DataInfo<number>>(sessionKey)?.roles[0]
          )
        ]
      : [],
    taskType: localStorage.getItem("taskType") ?? null,
    competitionStartTime: localStorage.getItem("competitionStartTime") ?? "",
    competitionEndTime: localStorage.getItem("competitionEndTime") ?? ""
  }),
  actions: {
    /** 存储用户名 */
    SET_USERNAME(username: string) {
      this.username = username;
    },
    /** 存储角色 */
    SET_ROLES(roles: Array<string>) {
      this.roles = roles;
    },
    SET_TaskType(taskType: number) {
      this.taskType = taskType;
    },
    /** 存储倒计时 */
    SET_CompetitiontartTime(competitionStartTime: string) {
      this.competitionStartTime = competitionStartTime;
    },
    SET_CompetitionEndTime(competitionEndTime: string) {
      this.competitionEndTime = competitionEndTime;
    },
    /** 登入 */
    async loginByUsername(data) {
      return new Promise<UserResult>((resolve, reject) => {
        getLogin(data)
          .then(data => {
            // console.log("loginByUsername-data", data);
            if (data.success) {
              setToken(data.data);
            }
            resolve(data);
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    /** 前端登出 */
    async logOut() {
      // const userId = decrypt();
      const userId = decrypt(localStorage.getItem("userId"));

      const data = qs.stringify({
        userId: userId
      });
      await getLogout(data);
      this.username = "";
      this.roles = [];
      removeToken();
      useMultiTagsStoreHook().handleTags("equal", [...routerArrays]);
      resetRouter();
      window.location.reload();
      router.push("/login");
    },
    /** 刷新`token` */
    async handRefreshToken(data) {
      window.location.reload();
      router.push("/login");
      removeToken();
      ElMessage.error("登录已过期请重新登录");
      // return new Promise<RefreshTokenResult>((resolve, reject) => {
      //   refreshTokenApi(data)
      //     .then(data => {
      //       if (data) {
      //         if (data.success) {
      //           setToken(data.data);
      //           resolve(data);
      //         } else {
      //           ElMessage.error(data.msg);
      //           router.push("/login");
      //           removeToken();
      //         }
      //       }
      //     })
      //     .catch(error => {
      //       reject(error);
      //     });
      // });
    }
  }
});

export function useUserStoreHook() {
  return useUserStore(store);
}
